const Koa = require("koa");
const app = new Koa();
const router = require("koa-router")();
const bodyparser = require("koa-bodyparser");
const query = require("./mysql")
//获取数据
router.get("/list",async ctx=>{
    const res = await query(`select * from aaa`);
    ctx.body={
        code:1,
        msg:"成功获取用户列表",
        res
    }
})
//添加数据
// router.post("/post",async ctx=>{
//     const {name,mima}=ctx.request.body
//     const res=await query(`insert into aaa (name,mima) values (?,?)`,
//     [name,mima])
//     ctx.body=res
//     // console.group(name,mima)
// })

//添加用户
router.post('/post', async (ctx) => {
    //获取请求体参数
    const { name, mima } = ctx.request.body;
    //非空校验
    if (!name || !mima) {
        ctx.body = {
            code: 403,
            message: '参数不合法'
        }
    }
    let res = await query('insert into user (name,mima) values (?,?)', [name, mima]);
    //判断用户是否添加成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 403,
            message: '添加用户失败'
        }
    }
    ctx.body = {
        code: 200,
        message: '添加成功'
    }
})

//更新数据

// router.put("/put/:id",async ctx=>{
//     const {id} = ctx.params
//     const {name,mima} = ctx.request.body;
//     const user =await query(`select * from aaa`);
//     if(user.length===0){
//         ctx.body={
//             code:404,
//             msg:"失败"
//         }
//     }
//     let res = user[0]
//     let params = [
//         name?name:res.name,
//         mima?mima:res.mima,
//         id
//     ]
//     res = await query(`update aaa set name=?,mima=? where id=?`,params)
//     ctx.body={
//         code:1,
//         msg:"更新成功"
//     }
// })

router.put('/put',async ctx=>{
    const {name,mima,id}=ctx.request.body;
    const res=await query(`update aaa set name=?,mima=? where id=?`,[name,mima,id])
    ctx.body={
        code:1,
        msg:"更新成功"
    }
})

//删除数据
router.delete('/del',async ctx=>{
    const {id}=ctx.query;
    const res=await query(`delete from aaa where id=?`,[id])
    ctx.body={
        code:1,
        msg:"删除成功"
    }
})


app.use(bodyparser());
app.use(router.routes());
app.listen(9000,()=>{
    console.log("服务已启动，http://localhost:9000")
})